/**
 * 立即验票
 */

import React, { Component } from 'react'
import {
  View, Text, StyleSheet, Image, TouchableOpacity, TextInput,StatusBar,Keyboard,TouchableWithoutFeedback
} from 'react-native'
import NavPage from '../../common/NavPage'
import SafeView from 'react-native-safe-area-view'
import moment from 'moment'
import axios from 'axios'
import qs from 'qs'
import Screen from '../../common/screen'
import Toast from 'antd-mobile/lib/toast'
import ImageResources from '../../common/ImageResources'
import FetchResources from '../../common/FetchResources'
import GetSetStorge from '../../common/GetSetStorge'
// import * as WeChat from 'react-native-wechat'
import Alipay from '../../common/Alipay'
// import BackgroundTimer from 'react-native-background-timer'
import { RouteHelper } from 'react-navigation-easy-helper'

export default class Inspect extends Component{
  constructor(props) {
    super(props)
    let { consumptionId,code,number } = this.props.navigation.state.params
    this.state = {
      num:number || 1,
      number:number || 1,
      subBottom:0,
      addBottom:0,
      showInput:false,
      KeyboardShown:"",
      butSub:'Sub',
      butAdd:'Add',
      consumptionId : consumptionId || '',
      code : code || '',
      checkUser:''
    }
  }

  componentDidMount() {
    // Toast.loading('加载中...', 0)
    GetSetStorge.getStorgeAsync('loginInfo').then((result) => {
      if (result) {
        this.setState({checkUser:result.split('|')[0]})
      }
    }).catch((error) => {
      console.log('==========================')
      console.log('系统异常' + error)
      console.log('==========================')
    })

  }

  componentWillMount () {  
    //监听键盘弹出事件  
    this.keyboardDidShowListener = Keyboard.addListener(  
      "keyboardDidShow",  
      this.keyboardDidShowHandler.bind(this)  
    )
    //监听键盘隐藏事件  
    this.keyboardDidHideListener = Keyboard.addListener(  
      "keyboardDidHide",  
      this.keyboardDidHideHandler.bind(this)  
    ) 
  }  
    
  componentWillUnmount() {  
    //卸载键盘弹出事件监听  
    if (this.keyboardDidShowListener != null) {  
        this.keyboardDidShowListener.remove();  
    }  
    //卸载键盘隐藏事件监听  
    if (this.keyboardDidHideListener != null) {  
        this.keyboardDidHideListener.remove();  
    }  
  }   

  //键盘弹出事件响应  
  keyboardDidShowHandler(event) {  
    this.setState({ KeyboardShown: true });  
  }  

  //键盘隐藏事件响应  
  keyboardDidHideHandler(event) {  
    this.setState({ KeyboardShown: false });  
  }  

  lostBlur(){  
    //退出软件盘  
    let { number,num } = this.state
    if(number == null || number == ''){
      this.setState({number:num})
    }
    Keyboard.dismiss();    
  } 

  goBack() {
    RouteHelper.pop()
  }

  inspect(){
    let {consumptionId,code,number,checkUser} = this.state
    Toast.loading('验证中...', 0)
    axios.post(FetchResources.Fetch.CheckOrder,//购票接口
			qs.stringify({
        code,
        consumptionId,
        checkUser,
        useNum:number
			})
		).then((response) => {
      Toast.hide()
      if(response.data.success){//查询成功
        if(response.data.leftNum == 0){ // 剩余可验证次数为0，表示全部已验证
          Toast.info('验证完成', 1)
          this.setState({num:response.data.leftNum,number:response.data.leftNum})
          this.timer = setTimeout(() => {
            RouteHelper.navigate('TicketVerify')
          }, 1100)
        }else{
          this.setState({num:response.data.leftNum,number:response.data.leftNum})
          Toast.info(`剩余使用次数:${response.data.leftNum}次`, 1)
        }
        // RouteHelper.navigate('TicketVerify')

        // RouteHelper.navigate('PaySuccess',{consumptionName,consumptionId,total,number,payWay,code,state,orderTime})
      }else{
        Toast.info(`该验票码有效使用次数为0，请重新购票！`, 1)
        this.timer = setTimeout(() => {
          RouteHelper.navigate('TicketVerify')
        }, 1100)
      }
		}).catch((error) => {
      Toast.hide()
    })
 
  }

  addSubtract(type){
    this.lostBlur()
    let { number,num } = this.state
    if(number == null || number == ''){
      this.setState({number:num},()=>{
        this.addSub(type)
      })
    }else{
      this.addSub(type)
    }

  }

  addSub(type){
    let { number,num } = this.state
    if(type == 'add'){
      if(number < num){
        this.setState({
          number:parseInt(number)+1,
          addBottom:0,
          butAdd:'AddActived',
          butSub:'Sub'
        })
        this.timer = setTimeout(() => {
          this.setState({addBottom:0,butAdd:'Add'})
        }, 80)
      }else{
        this.setState({
          butAdd:'AddDisable'
        })
      }
      
    }else{
      if(this.state.number>1){
        this.setState({
          number:parseInt(number)-1,
          subBottom:0,
          butSub:'SubActived',
          butAdd:'Add'
        })
        this.timer = setTimeout(() => {
          this.setState({subBottom:0,butSub:'Sub'})
        }, 80)
      }else{
        this.setState({
          butSub:'SubDisable'
        })
      }
    }
  }

  onChangeNum(number){
    let { num } = this.state
    if(number < num){
      this.setState({number})
    }
  }

  render() {
    const dismissKeyboard = require('dismissKeyboard'); 
    let { payWay, total,cash,number,price,num ,showInput,butSub,butAdd} = this.state

    return (
      <SafeView style={styles.container} forceInset={{ top: 'never' }}>
        <StatusBar
          animated={true}
          hidden={false}
          backgroundColor={'#111'}
          translucent={true}
          barStyle={'light-content'}
          showHideTransition={'fade'}
          networkActivityIndicatorVisible={true}
        />
        <TouchableWithoutFeedback onPress={this.lostBlur.bind(this)}>
        <View style={{flex:1}}>
          <NavPage goBack={this.goBack.bind(this)} title={''} showGoBack={true} bgColor={'#F6F7F8'} />

          <View style={{flex:1}}>
            <View style={styles.goodsBox}>
              <Text style={{fontSize:24,color:'#111',fontWeight:'500',textAlign:'left',marginLeft:40,marginBottom:10}}>验票</Text>
              <View style={{flex:1,justifyContent: 'center',alignItems:'center',borderRadius:5}}>
                <View style={{flex:1,flexDirection:'column',justifyContent: 'center',alignItems:'center',backgroundColor:'#fff',width:Screen.width*0.9,borderRadius:5,padding:10}}>
                  <View style={{height:30,flexDirection:'row',paddingHorizontal:4}}>
                    <Text style={{flex:1,fontSize:16}}>票数</Text>
                    <Text style={{flex:1,textAlign:'right',fontSize:16}}>验证数量</Text>
                  </View>

                  <View style={{flex:1,flexDirection:'row',}}>
                    <Text style={{flex:2,fontSize:32,color:'#FF9700',fontWeight:'500'}}>{num}次</Text>
                    <View style={{flex:1.5,flexDirection:'row',justifyContent: 'flex-end',alignItems:'center',height:45}}>
                      <TouchableOpacity activeOpacity={0.8} onPress={this.addSubtract.bind(this,'subtraction')} >
                        <Image style={[{width:40,height:40,padding:0,marginBottom:this.state.subBottom}]} source={number == 1 ?ImageResources.PayIcon['SubDisable'] : ImageResources.PayIcon[butSub]}  />
                      </TouchableOpacity>
                    
                        <TextInput
                          placeholder=""
                          underlineColorAndroid="transparent"
                          keyboardType={'numeric'}
                          returnKeyType={'next'}
                          // onSubmitEditing={() => this.refs.password.focus()}
                          maxLength={11}
                          placeholderTextColor='#ccc'
                          style={{width:32,paddingBottom:4,textAlign:'center'}}
                          value={`${number}`}
                          defaultValue={`${number}`}
                          onChangeText={(number) => number <= num ? this.setState({ number }) : (number == ''||number == NaN ? this.setState({ number:num }) : null) }
                          
                        />  
                    
                      <TouchableOpacity activeOpacity={0.8} onPress={this.addSubtract.bind(this,'add')} >
                        <Image style={[{width:40,height:40,marginBottom:this.state.addBottom}]} source={number == num ? ImageResources.PayIcon['AddDisable'] : ImageResources.PayIcon[butAdd]}  />
                      </TouchableOpacity>
                    </View>
                  </View>

                </View>
              </View>
            </View>
          </View>

          <TouchableOpacity onPress={this.inspect.bind(this)} style={{marginBottom:30}}>
            <View style={{justifyContent: 'center',alignItems:'center',width:Screen.width}}>
                <Text style={{ color: '#5D7194',fontSize:16,borderWidth:1,borderColor:'#5C7094',borderRadius:24,paddingVertical:12,width:Screen.width*0.79,textAlign:'center'}}>确认验证</Text>
            </View>
          </TouchableOpacity>
          </View>
        </TouchableWithoutFeedback>
      </SafeView>
    )
  }
}


const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#F6F7F8',
    flexDirection:'column'
  },
  goodsBox:{
    height:150,
    borderRadius:4,
    padding:10
  },
  buttons:{
    fontSize: 16,
    textAlign:'center',
    width:25,
    height:25,
    borderColor:'#bbb',
    borderRadius:12.5,
    borderStyle:'solid',
    borderWidth:1,
  },
  item: {
    height:68,
    backgroundColor: '#fff',
    alignItems: 'center',
    paddingHorizontal: 10,
    marginBottom:10,
    flexDirection: 'row',
    borderRadius:5
  },
  yue: {
    padding: 20,
    alignItems: 'center'
  },
  txt: {
    borderWidth: 1,
    borderColor: '#eee',
    width: Screen.width * 0.5,
    height: 40,
    paddingHorizontal: 10,
    marginBottom: 10
  },
  icon: {
    width: 35,
    height: 30,
    marginRight: 10,
  },
  selectIcon: {
    width: 17,
    height: 17
  },
  foot: {
    height: 45,
    flexDirection: 'row',
    width: Screen.width,
    backgroundColor: '#fff'
  },
  footLeft: {
    width: Screen.width * 0.6,
    flexDirection: 'row',
    backgroundColor: '#fff',
    alignItems: 'center',
    paddingLeft: 20
  },
  footRight: {
    backgroundColor: '#52B45D',
    width: Screen.width * 0.4,
    justifyContent: 'center',
    alignItems: 'center'
  }
})